/**
 * @format
 * @Author: TC
 * @Date: 2023-02-22 11:03:51
 * @LastEditTime: 2023-02-22 11:52:07
 * @Description:
 */

import { IBaseInterface } from "../../Interface/BaseInterface";
import { IEventInstance } from "./EventInterface";

/**
 * 事件单位
 */
export class EventUnit implements IBaseInterface {
    private _listEvent: IEventInstance[] = [];

    constructor(iEvent: IEventInstance) {
        this.addListener(iEvent);
    }

    public get listEvent(): IEventInstance[] {
        return this._listEvent;
    }

    /**
     * 添加回调
     */
    public addListener(iEvent: IEventInstance): void {
        this._listEvent.push(iEvent);
    }

    /**
     * 执行
     */
    public execute(arg: any): void {
        this._listEvent.forEach((e) => {
            e.callback.call(e.thisObj, arg);
        });
    }

    /**
     * 注销某个对象上注册的事件
     * @param thisObg
     */
    removeListenerByTarget(thisObg: any): void {
        for (let i = 0, len = this._listEvent.length; i < len; i++) {
            if (this._listEvent[i].thisObj === thisObg) {
                this._listEvent.splice(i, 1);
                len--;
            }
        }
    }

    release(): void {
        this._listEvent.forEach((e) => {
            e = null;
        });
        this._listEvent.length = 0;
        this._listEvent = null;
    }
}
